import {
  createBrowserRouter,
  RouterProvider as BrowserRouterProvider,
} from "react-router-dom";
import { getRoutes } from "./routes";
import { Suspense } from "react";
function buildTree(departments, routeComponents) {
  const map = new Map();
  let root;

  departments.forEach((item) => {
    const View = routeComponents?.[item?.id];
    map.set(item.id, {
      ...item,
      element: (
        <Suspense fallback={<div>Loading...</div>}>
          <View />
        </Suspense>
      ),
      children: [],
    });
    if (item.pid === "0") {
      root = map.get(item.id);
    } else {
      const parent = map.get(item.pid);
      if (parent) {
        parent.children.push(map.get(item.id));
      }
    }
  });

  return [root];
}

export const RouterProvider = () => {
  const { routes, routeComponents } = getRoutes();
  const router = createBrowserRouter(buildTree(routes, routeComponents));
  return <BrowserRouterProvider router={router} />;
};
